import { reqCategoryList1, reqCategoryList2,reqCategoryList3 } from '@/api/category'
import { Message } from 'element-ui'
const state = {
    category1Id: '',
    category2Id: '',
    category3Id: '',
    categoryList1: [],
    categoryList2: [],
    categoryList3: [],
}
const mutations = {
    SET_CATEGORYLIST1(state, categoryList1) {
        state.categoryList1 = categoryList1
    },
    UPDATE_CATEGORY1ID(state, category1Id) {
        state.category1Id = category1Id
    },
    SET_CATEGORYLIST2(state, categoryList2) {
        state.categoryList2 = categoryList2
    },
    UPDATE_CATEGORY2ID(state, category2Id) {
        state.category2Id = category2Id
    },
    SET_CATEGORYLIST3(state, categoryList3) {
        state.categoryList3 = categoryList3
    },
    UPDATE_CATEGORY3ID(state, category3Id) {
        state.category3Id = category3Id
    },
}
const actions = {
    // 获取一级分类
    async getCategoryList1({commit}) {
        try {
            const res = await reqCategoryList1()
            commit('SET_CATEGORYLIST1',res.data)
        } catch (error) {
            Message.error('获取一级分类失败')
        }
    },
    // 获取二级分类
    async getCategoryList2({commit}, category1Id) {
        // 获取二级分类之前需要将2Id、3Id、3list清空
        commit('UPDATE_CATEGORY2ID', '')
        commit('UPDATE_CATEGORY3ID', '')
        commit('SET_CATEGORYLIST3',[])
        try {
            const res = await reqCategoryList2(category1Id)
            commit('UPDATE_CATEGORY1ID', category1Id)
            commit('SET_CATEGORYLIST2', res.data)
            return Promise.resolve('ok')
        } catch (error) {
            Message.error('获取二级分类失败')
        }
    },
    // 获取三级分类
    async getCategoryList3({ commit }, category2Id) {
        // 获取三级分类之前要将3Id清空
        commit('UPDATE_CATEGORY3ID', '')
        try {
            const res = await reqCategoryList3(category2Id)
            commit('UPDATE_CATEGORY2ID', category2Id)
            commit('SET_CATEGORYLIST3', res.data)
            return Promise.resolve('ok')
        } catch (error) {
            Message.error('获取三级分类失败')
        }
    },
    // 保存三级分类id
    saveCategory3Id({commit},category3Id) {
        commit('UPDATE_CATEGORY3ID',category3Id)
    }
}
const getters = {

}
export default {
    namespaced:true,
    state,
    mutations,
    actions,
    getters
}